package model

import (
	"database/sql"
	"fmt"
	"strings"
	"time"

	"github.com/tal-tech/go-zero/core/stores/sqlc"
	"github.com/tal-tech/go-zero/core/stores/sqlx"
	"github.com/tal-tech/go-zero/core/stringx"
	"github.com/tal-tech/go-zero/tools/goctl/model/sql/builderx"
)

var (
	procDefFieldNames          = builderx.RawFieldNames(&ProcDef{})
	procDefRows                = strings.Join(procDefFieldNames, ",")
	procDefRowsExpectAutoSet   = strings.Join(stringx.Remove(procDefFieldNames, "`id`", "`create_time`", "`update_time`"), ",")
	procDefRowsWithPlaceHolder = strings.Join(stringx.Remove(procDefFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"
)

type (
	ProcDefModel interface {
		Insert(data ProcDef) (sql.Result, error)
		FindOne(id int64) (*ProcDef, error)
		FindOneByGroupKey(group string, key string) (*ProcDef, error)
		Update(data ProcDef) error
		Delete(id int64) error
		FindByGroup(group string, page ...Page) ([]*ProcDef, error)
	}

	defaultProcDefModel struct {
		conn  sqlx.SqlConn
		table string
	}

	ProcDef struct {
		Id         int64     `db:"id"`
		Key        string    `db:"key"`     // 流程定义的唯一标识，同一个group中key是唯一的
		Group      string    `db:"group"`   // 流程定义组名
		Title      string    `db:"title"`   // 展示用的流程名称
		Content    string    `db:"content"` // 流程定义的内容
		CreateTime time.Time `db:"create_time"`
		UpdateTime time.Time `db:"update_time"`
	}
)

func NewProcDefModel(conn sqlx.SqlConn) ProcDefModel {
	return &defaultProcDefModel{
		conn:  conn,
		table: "`proc_def`",
	}
}

func (m *defaultProcDefModel) Insert(data ProcDef) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?)", m.table, procDefRowsExpectAutoSet)
	ret, err := m.conn.Exec(query, data.Key, data.Group, data.Title, data.Content)
	return ret, err
}

func (m *defaultProcDefModel) FindOne(id int64) (*ProcDef, error) {
	query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", procDefRows, m.table)
	var resp ProcDef
	err := m.conn.QueryRow(&resp, query, id)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultProcDefModel) FindOneByGroupKey(group string, key string) (*ProcDef, error) {
	var resp ProcDef
	query := fmt.Sprintf("select %s from %s where `group` = ? and `key` = ? limit 1", procDefRows, m.table)
	err := m.conn.QueryRow(&resp, query, group, key)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultProcDefModel) Update(data ProcDef) error {
	query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, procDefRowsWithPlaceHolder)
	_, err := m.conn.Exec(query, data.Key, data.Group, data.Title, data.Content, data.Id)
	return err
}

func (m *defaultProcDefModel) Delete(id int64) error {
	query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
	_, err := m.conn.Exec(query, id)
	return err
}

func (m *defaultProcDefModel) FindByGroup(group string, page ...Page) ([]*ProcDef, error) {
	panic("implement me")
}
